export default {
  created() {
    this.getUserList();
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (!/^1[356789]\d{9}$/.test(value)) {
        callback(new Error("手机号格式不正确"));
      }
      callback();
    };
    return {
      // 用户列表数据
      pageData: {
        query: "",
        pagenum: 1,
        pagesize: 5
      },
      usersList: [],
      //   总页数
      total: 0,
      //   添加用户对话框
      dialogVisible: false,
      //   分配权限对话框
      roleDialogFormVisible: false,
      //   添加用户
      form: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //   分配角色
      roleUsername: "",
      roleId: null,
      role_name: "",
      roleList: [],
      roleSelected: "",
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: validateMobile,
            trigger: "blur"
          }
        ]
      },
      //   编辑用户
      editForm: {
        id: "",
        username: "",
        email: "",
        mobile: ""
      },
      editDialogFormVisible: false,
      editRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: validateMobile,
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    async getUserList() {
      var {
        data: { data, meta }
      } = await this.$http.get("users", { params: this.pageData });
      //   console.log(meta);
      // console.log(data);
      if (meta.status !== 200) return this.$message.error(meta.msg);
      this.usersList = data.users;
      this.total = Math.ceil(data.total / this.pageData.pagesize);
      // console.log(this.usersList);
    },
    searchUser() {
      this.getUserList();
    },
    pageChange(newPageNum) {
      //   console.log(newPageNum);
      //   更新新的页码
      this.pageData.pagenum = newPageNum;
      this.getUserList();
    },
    // 添加用户表单验证
    addUserSubmit() {
      this.$refs.addUserForm.validate(async valid => {
        // console.log(valid);
        // console.log(this.$refs.addUserForm.value);

        if (valid) {
          var {
            data: { meta }
          } = await this.$http.post("users", this.form);
          if (meta.status !== 201) {
            return this.$message.error(meta.msg);
          }
          this.$message.success("用户添加成功");
          this.getUserList();
          //   且页面切换到第一页
          this.pageData.pagenum = 1;
          this.dialogVisible = false;
        }
      });
    },
    // 重置表单
    resetUserForm() {
      // 显示对话框
      this.dialogVisible = true;
      // 渲染DOM需要时间，此时获取不到DOM元素
      //   window.setTimeout(() => {
      //     this.$refs.addUserForm.resetFields();
      //   }, 0);
      this.$nextTick(() => {
        this.$refs.addUserForm.resetFields();
      });
    },
    // 改变用户状态
    async changeState(user) {
      // 获取当前用户状态，
      //   console.log(user);
      var {
        data: { meta }
      } = await this.$http.put("users/" + user.id + "/state/" + user.mg_state);
      if (meta.status !== 200) {
        return this.$message.error(meta.msg);
      }
      this.$message.success(meta.msg);
    },
    // 删除用户
    async delUser(id) {
      //   console.log(id);
      this.$confirm("您确定删除该管理员吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          var {
            data: { meta }
          } = await this.$http.delete("users/" + id);
          //   console.log(meta);
          if (meta.status !== 200) {
            return this.$message.error(meta.msg);
          }
          this.$message.success(meta.msg);
          this.getUserList();
        })
        .catch(() => null);
    },
    // 获取角色列表
    async getRoleList(role) {
      var {
        data: { data, meta }
      } = await this.$http.get("roles");
      //   console.log(meta);
      //   console.log(data);
      if (meta.status !== 200) return this.$message.error(meta.msg);
      this.roleSelected = "";
      this.roleDialogFormVisible = true;
      this.roleUsername = role.username;
      this.roleId = role.id;
      this.role_name = role.role_name;
      this.roleList = data;
    },
    // 修改角色
    async changeRole() {
      var {
        data: { meta }
      } = await this.$http.put(`users/ ${this.roleId} /role`, {
        rid: this.roleSelected
      });
      if (meta.status !== 200) return this.$message.error(meta.msg);
      this.$message.success(meta.msg);
      this.getUserList();
      this.roleDialogFormVisible = false;
    },
    // 打开编辑用户对话框
    async openeditDialog(row) {
      this.editDialogFormVisible = true;
      //    等待对话框加载完成
      this.$nextTick(() => {
        // 重置表单数据
        // this.$refs.editForm.resetFields();
        this.$refs.editForm.resetFields();
        // 把获取到的值填充到当前表单域
        this.editForm.id = row.id;
        this.editForm.username = row.username;
        this.editForm.email = row.email;
        this.editForm.mobile = row.mobile;
      });
    },
    // 提交编辑用户信息
    editUser() {
      // 对整个表单做校验
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          var {
            data: { meta }
          } = await this.$http.put(`users/${this.editForm.id}`, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          });
          if (meta.status !== 200) return this.$message.error(meta.msg);
          this.getUserList();
          this.editDialogFormVisible = false;
        }
      });
    }
  }
};
